USE [data]
GO

/****** Object:  UserDefinedFunction [monica].[fn_data_seg_crypt]    Script Date: 02/29/2012 15:23:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[monica].[fn_data_seg_crypt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [monica].[fn_data_seg_crypt]
GO

USE [data]
GO

/****** Object:  UserDefinedFunction [monica].[fn_data_seg_crypt]    Script Date: 02/29/2012 15:23:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [monica].[fn_data_seg_crypt] (@caso char(1), @clave_in varchar(11))
RETURNS varchar(20)
begin
declare 
 @clave_out varchar(20),
 @len_data_in int,  
 @li_c_patron int,  
 @li_c_clave  int,  
 @li_c_new int ,  
 @li int ,    
 @patron_cambio varchar(10)  
  
set @patron_cambio = ')(*&^%$#@!'  
set @clave_out = ''  
set @len_data_in = DATALENGTH(@clave_in)  
set @li = 1  
while @len_data_in >  @li -1  
begin   
 set @li_c_patron =ASCII( substring(@patron_cambio,@li,1))  
 set @li_c_clave =ASCII( substring(@clave_in,@li,1))  
 /*select substring(@clave_in,@li,1)*/   
 if @caso = 'C'  
  set @li_c_new = @li_c_clave  + @li_c_patron  
 else  
  begin   
   if @li_c_clave  + @li_c_patron > 255  
    set @li_c_new = @li_c_clave   
   else  
    set @li_c_new = @li_c_clave  - @li_c_patron  
  end   
 if @li_c_new > 255  
  set @li_c_new = @li_c_clave   
 set @clave_out = @clave_out + CHAR(@li_c_new)  
 set @li =  @li + 1  
end  
set @clave_out = ltrim(@clave_out)  

return @clave_out
end

GO
GRANT EXECUTE ON [monica].fn_data_seg_crypt   TO SATABLET

